# This file is part of The Vu Toolkit.
#
# The Vu Toolkit is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# The Vu Toolkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with The Vu Toolkit; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307 USA.
#
# Copyright © Zak Fenton 2008
#

require 'rexml/document'

module Vu::SVG
	# Class used to read in an SVG tree from XML.
	# Note: I'm not great with XML, this might look ugly/entirely incorrect.
	class Reader
		# Parse a REXML Document, returning an SVG object
		def self.read_doc (d)
			read_node(d.root)
		end
		
		def self.read_node (xml)
			obj = nil
			case xml.name
				when "svg"
					obj = SVG.new
				when "rect"
					obj = Rect.new
				when "desc"
					# ignore
				when "g"
					obj = Group.new
				else
					puts "UNKNOWN #{xml.name}"
			end
			
			if obj
				apply_attrs(xml,obj)
				add_children(xml,obj)
			end
			
			return obj
		end
		
		def self.add_children (xml,obj)
			for c in xml.children
				if c.is_a?(REXML::Element)
					n = read_node(c)
					if n
						obj.add_child(n)
					end
				end
			end
		end
		
		def self.apply_attrs (xml, obj)
			for key,val in xml.attributes
				case key
					when 'viewBox'
						obj.view_box = Bounds.parse(val)
					when 'x'
						obj.x = Abstract.parse(val)
					when 'y'
						obj.y = Abstract.parse(val)
					when 'width'
						obj.width = Abstract.parse(val)
					when 'height'
						obj.height = Abstract.parse(val)
					when 'rx'
						obj.rx = Abstract.parse(val)
					when 'ry'
						obj.ry = Abstract.parse(val)
					when 'stroke'
						obj.stroke = Paint.parse(val)
					when 'fill'
						obj.fill = Paint.parse(val)
					when 'stroke-width'
						obj.stroke_width = val.to_f
					when 'transform'
						obj.transform.apply!(Transformation.parse(val))
					else
						puts "UNKNOWN ATTRIBUTE #{key} (= #{val})"
				end
			end
		end
		
		# Open a file and reads it in
		def self.read_file (f)
			read_doc(REXML::Document.new(File.new(f)))
		end
	end
end

